package gb.demo.controller;

import com.alibaba.druid.pool.WrapperAdapter;
import com.alibaba.druid.sql.dialect.oracle.ast.clause.ModelClause;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import gb.demo.common.R;
import gb.demo.entity.Email;
import gb.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import gb.demo.entity.User;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Controller
@MapperScan("gb.demo.mapper")
public class UserController {
    @Autowired
    private UserService userService;
    private Email emaiL = new Email();
    @Autowired
    private JavaMailSender mailSender;

    @RequestMapping("/user/sendemail")
    @ResponseBody
    public R sendCode(String email) {
        emaiL.setEmail(email);
        emaiL.newCode();
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("2388505323@qq.com");
        message.setTo(emaiL.getEmail());
        message.setSubject("NTR俱乐部验证");
        message.setText("您好:\n"
                + "\n您正在注册人妻论坛，本次请求的邮件验证码为:" + emaiL.getCode() + ",本验证码 5 分钟内效，请及时输入。（请勿泄露此验证码）\n"
                + "\n如非本人操作，请忽略该邮件。\n(这是一封通过自动发送的邮件，请不要直接回复）");
        mailSender.send(message);
        System.out.println(emaiL);
        return R.success("发送成功");
    }


    @GetMapping("/user/userManagePage")
    public String userManagePage() {
        return "User/userManagement";
    }

    @RequestMapping("/user/allUser")
    @ResponseBody
    public R Test(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user != null && user.getIsadmin() == 1) {
            List<User> users = userService.list();
            return R.success(users);
        } else return R.error("请登录管理员账号后重试");
    }

    @GetMapping("/")
    public String index() {
        return "user/login";
    }

    @GetMapping("/user/loginPage")
    public String loginPage() {
        return "user/login";
    }

    @GetMapping("/user/registerPage")
    public String registerPage() {
        return "user/register";
    }

    @GetMapping("/user/updatePage")
    public String updatePage() {
        return "User/userUpdate";
    }

    //    登录
    @PostMapping("/user/login")
    @ResponseBody
    public R login(String username, String password, HttpServletRequest request, HttpSession session, HttpServletResponse response) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        String passwordMd5= DigestUtils.md5DigestAsHex(password.getBytes());
        queryWrapper.eq(User::getUsername, username).eq(User::getPassword, passwordMd5);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            //登录失败
            return R.error("用户名或密码错误");
        }
        if(user.getIsadmin()==-1){
            return R.error("账户已被禁用");
        }
        session.setAttribute("loginUser", user);
        System.out.println("测试 " + session.getAttribute("loginUser"));
        return R.success(user);
    }

    //    注册
    @PostMapping("/user/register")
    @ResponseBody
    public R register(User user, String code) {
        System.out.println(emaiL.verify(code));
        System.out.println(System.currentTimeMillis() - emaiL.getDate());
        if (!emaiL.verify(code))
            return R.error("验证码错误");
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getUsername, user.getUsername());
        User registerUser = userService.getOne(queryWrapper);
        if (registerUser != null) {
            return R.error("用户名已存在");
        }
        String passwordMd5= DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(passwordMd5);
        userService.save(user);
        return R.success(user);
    }

    //  注销
    @GetMapping("/user/logout")
    public String logout(HttpServletRequest request, HttpSession session, HttpServletResponse response) {
        //清空cookie
        Cookie cookie = new Cookie("username", null);
        cookie.setMaxAge(0);   //删除cookie
        cookie.setPath(request.getContextPath() + "/");    //设置cookie存在的路径
        response.addCookie(cookie);

        //销毁session
        session.invalidate();

        return "redirect:/";    //重定向到首页
    }

    //   信息管理
    @RequestMapping("/user/updata")
    @ResponseBody
    public R userUpdata(String nickname, String password, String code, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user != null) {
            if (emaiL.verify(code)) {
                UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
                String passwordMd5= DigestUtils.md5DigestAsHex(password.getBytes());
                userUpdateWrapper.eq("username", user.getUsername()).set("nickname", nickname).set("password", passwordMd5);
                userService.update(null, userUpdateWrapper);
                return R.success("修改成功");
            } else return R.error("验证码错误");
        } else return R.error("请登陆账号后重试");
    }

    //    管理员修改信息
    @RequestMapping("/user/updateByAdmin")
    @ResponseBody
    public R userUpdataByAdmin(String username, String nickname, String password, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user != null && user.getIsadmin() == 1) {
            UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
            String passwordMd5= DigestUtils.md5DigestAsHex(password.getBytes());
            userUpdateWrapper.eq("username", username).set("nickname", nickname).set("password", passwordMd5);
            userService.update(null, userUpdateWrapper);
            return R.success("修改成功");
        } else return R.error("请登陆管理员账号后重试");
    }

    //    修改邮箱
    @RequestMapping("/user/updateEmail")
    @ResponseBody
    public R updateEmail(String mail, String code, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user != null) {
            if (emaiL.verify(code)) {
                UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
                userUpdateWrapper.eq("username", user.getUsername()).set("email", mail);
                userService.update(null, userUpdateWrapper);
                return R.success("修改成功");
            } else return R.error("验证码错误");
        } else return R.error("请登陆后重试");
    }

    //    删除用户
    @RequestMapping("/user/delete")
    @ResponseBody
    public R userDelete(String userId, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user != null && user.getIsadmin() == 1) {
            UpdateWrapper<User> userUpdateWrapper=new UpdateWrapper<>();
            userUpdateWrapper.eq("userid",userId).set("isadmin",-1);
            if(userService.update(userUpdateWrapper))
                return R.success("禁用成功");
            else return R.error("禁用失败");
        } else return R.error("请登录管理员账号重试");
    }

    //    检查是否登录
    @RequestMapping("/user/isLogin")
    @ResponseBody
    public R checkLogin(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user != null) {
            return R.success(user);
        } else return R.error("请登录后重试");
    }
}
